#include "gdl703t.h"
#include <pthread.h> //多线程
#include <signal.h>

void* init(){
    //初始化设备与管道
    devID = gdl703t_init(2);

    //开始获取音频数据
    gdl703t_start('a');
}

void* data_handle(){

    pipo_R_date_out_fd = pipe_open_read(PIPE_R_PATH);

    while (1)
    {
#if COMMUNICATION_MODE == MQUEUE
        mqueue_receive('r');
#elif COMMUNICATION_MODE == PIPE
        pipe_receive('r');
        pipe_receive('l');
#else
    #error "Invalid communication mode!"
#endif
    }
    
}
//异常退出处理函数
void sigint_handler(int sig)
{
#if COMMUNICATION_MODE == MQUEUE
    mqueue_cloes('r');
    mqueue_delete('r');
#elif COMMUNICATION_MODE == PIPE
    pipe_cloes(pipo_R_data_fd,PIPE_R_PATH);
    pipe_cloes(pipo_L_data_fd,PIPE_L_PATH);
#else
    #error "Invalid communication mode!"
#endif
    printf("Received SIGINT signal!\n");
    exit(1);
}

int main(){
    printf("分体式网络拾音器 多线程~~~\n\r");

    // 注册信号处理函数(异常退出的处理:ctrl+C)
    signal(SIGINT, sigint_handler);

    pthread_t write_th,read_th;//数据发送线程与数据接收线程
    pthread_create(&write_th,NULL,init,NULL);
    sleep(4);
    pthread_create(&read_th,NULL,data_handle,NULL);

    while (1)
    {
        sleep(1);
        printf(">>> DB=%d \n\r",getDB_char('r'));
    }
    
    //关闭相关资源
    gdl703t_stop(devID);
#if COMMUNICATION_MODE == MQUEUE
    mqueue_cloes('r');
    mqueue_delete('r');
#elif COMMUNICATION_MODE == PIPE
    pipe_cloes(pipo_R_data_fd,PIPE_R_PATH);
#else
    #error "Invalid communication mode!"
#endif

    return 0;
}


